import os
import tkinter

# import win32api

from config import BASC, PDF_WIDTH
from PIL import Image, ImageTk
# from PIL.Image import Resampling
from def_pack.doc_handle import DocHandle
from def_pack.entry_handle_small_frame import creat_a_entry_frame, get_the_input_content
from def_pack.mouse_scroll import space_contral_scroll
from def_pack.normal_solve import se_every_file_in_normal
from functools import partial
# import keyboard
# import win32con
# from subprocess import call
import threading
from natsort import ns, natsorted

def event1(canvas,event):
    """
    事件的属性 delta 解析
    在MouseWheel 事件中,正值代表上卷,负值代表下卷;
    在 Window 下,通常是 120 的倍数;在 MacOS 下,为 1 的倍数
    """
    number = int(-event.delta / 120)
    canvas.yview_scroll(number, 'units')

def event2(canvas,event):
    """
    事件的属性 delta 解析
    在MouseWheel 事件中,正值代表上卷,负值代表下卷;
    在 Window 下,通常是 120 的倍数;在 MacOS 下,为 1 的倍数
    """
    number = int(-event.delta / 120)
    canvas.yview_scroll(number, 'units')

#先打印出按键
# def key(event):
#     print( "pressed", repr(event.char))

def sayhellow(pic_name,clsdoc,event,choose_num=0):
    outstr=None
    if choose_num==0:
        outstr=pic_name
        clsdoc.gloco(outstr)
    #这是做视频的图片筛选的
    if choose_num==1:
        #这里还要生成一个界面
        outstr=f"{pic_name}"
        creat_a_entry_frame(outstr, clsdoc, cls=1)
    # 这是图片重命名标签
    if choose_num == 2:
        # 这里还要生成一个界面
        outstr = f"{pic_name}"
        creat_a_entry_frame(outstr, clsdoc, cls=1,kknum=1)


    return "break"

    # print(f"{pic_name}")


#这是resize函数
def resize_pic_num(ya,xa,size_num):
    if xa>int(size_num-20):
        return int((int(ya)*int(size_num-20))/xa)
    else:
        return ya

#对图片进行处理及输出
def handle_pic(filelist,img_png_list,image_open_list,frame_gd,frame_kd):
    for mm in filelist:
        # im_num=im_num+1
        # image_path=f"{BASC}/image/088.jpg"
        img_open = Image.open(mm)


        width1, height1 = img_open.size
        height1 = resize_pic_num(height1, width1,frame_kd)
        # img_open=img_open.resize((int(700), int(height1)), Image.LANCZOS)
        if height1<frame_gd:
            img_open=img_open.resize((int(int(frame_kd-20)), int(height1)), Image.Resampling.LANCZOS)
        else:
            img_open = img_open.resize((int(int(frame_kd - 20)), int(frame_gd)), Image.Resampling.LANCZOS)
        # img_open=img_open.resize((int(frame_kd-20), int(height1)))

        img_png = ImageTk.PhotoImage(img_open)

        img_png_list.append(img_png)
        image_open_list.append(img_open)
    return img_png_list,image_open_list


#对图片不做任何处理，原图片输出
#这里应该是按固定纵横比去裁剪
def handle_pic_normal_pic(filelist,img_png_list,image_open_list,frame_gd,frame_kd):
    for mm in filelist:
        img_open = Image.open(mm)
        width1, height1 = img_open.size
        height12=int(((frame_kd - 20)*height1)/width1)

        img_open = img_open.resize((int(int(frame_kd - 20)), int(height12)), Image.Resampling.LANCZOS)


        img_png = ImageTk.PhotoImage(img_open)
        img_png_list.append(img_png)
        image_open_list.append(img_open)
    return img_png_list, image_open_list

#这里做个选择函数
def handle_pic_choi(filelist,img_png_list,image_open_list,frame_gd,frame_kd,chov_n=0):
    if chov_n==0:
        # 这里也是要控制输出
        img_png_list, image_open_list = handle_pic(filelist, img_png_list, image_open_list, frame_gd, frame_kd)
        return img_png_list, image_open_list
    if chov_n == 1:
        img_png_list, image_open_list = handle_pic_normal_pic(filelist, img_png_list, image_open_list, frame_gd, frame_kd)
        return img_png_list, image_open_list

#这是按键控制的
# def abc(x):
#     a = keyboard.KeyboardEvent(event_type='down', scan_code=57, name='space')
#     if x.event_type == a.event_type and x.scan_code == a.scan_code:
#         win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, -100)
#         print("滚动了")

class ImageShowMainFrameProgram():

    def __init__(self):

        #这里是是否按原图片，还是按窗口裁剪图片的
        #0就是窗口裁剪图片，图片跟窗口一样大
        #1就是，展示的图片比例，是原图片的长宽比。
        self.num_k=0

        #这个是根据参数，是否添加标签跟按钮的
        self.lo_num=0
        #或者不用改这个参数，直接重写那个函数就可以了。

        #所以，只要改上面那两个参数就可以了。


        #这是控制图片间隔的，修改的时候，可以改为0
        self.jgz_value = 30
        #因为这里就
        # if self.num_k==0:
        #     self.jgz_value = 30
        # else:
        #     self.jgz_value = 0


        #显示窗口宽度要改一下，因为你的图片大小可能不一样
        #宽
        # self.frame_kd = 700
        self.frame_kd = 700
        #高
        self.frame_gd = 710

        #右边要添加的多余的宽度
        self.add_w=20

        #这个不用改，随意更改，是图片的最大的宽度
        self.the_biggest_width = 0
        self.frame_r_width=0
        self.show_height=0
        # 绘制矩形,并将轮廓线设置为透明色，即不显示最外围的轮廓线，默认为黑色
        # rect = canvas.create_rectangle(x0, y0 + 100, x1, y1 + 100, fill='red', outline='')

        self.firdir=None

    #这是创建标签跟输入框的
    def creat_entry_and_tag_frame(self,canvas,im_num,pic_name,clsdoc,choose_num,main_win,nay,
                                  nax1,dirname,nax2):

        # locals()[f"image{im_num}"].addtag(locals()[f"tag{im_num}"])
        canvas.tag_bind(f"tag{im_num}", '<Button-1>',
                        partial(sayhellow, f"{pic_name}", clsdoc, choose_num=choose_num))

        # 输入框的坐标，nax1，nay，
        locals()[f"entry{im_num}"] = tkinter.Entry(main_win, width=10, relief="solid")
        # canvas.create_window((nax1,nay),height=30, width=30, window=locals()[f"entry{im_num}"])
        nay1 = nay + 3
        canvas.create_window((nax1, nay1), window=locals()[f"entry{im_num}"], anchor="nw")

        locals()[f"btn{im_num}"] = tkinter.Button(main_win, text=f"输出标签名", width=10, height=1,
                                                  # padx=10, pady=10,
                                                  bg="Lavender", font=("楷书", 11), fg="Peru",
                                                  command=partial(get_the_input_content,
                                                                  locals()[f"entry{im_num}"], f"{pic_name}", clsdoc,
                                                                  main_win, kknum=choose_num, whether_close=1,
                                                                  title=dirname)
                                                  )
        nay2 = nay1 - 3
        canvas.create_window((nax2, nay2), window=locals()[f"btn{im_num}"], anchor="nw")

    def __frame_button_show(self,image_open_list,img_png_list,filelist,canvas,clsdoc,
                          choose_num,main_win,dirname):
        # print(f"{self.frame_r_width}")
        # print(f"{self.frame_r_width-width1}")
        # 这是名称的x坐标
        nax = int((self.frame_kd - 20) / 2) - 135
        # 这是输入框的横坐标
        nax1 = nax + 110
        # 这是按钮的横坐标
        nax2 = nax1 + 80

        # 根据image_open_list展示标签，
        im_num = 0

        # 这是名称的展示坐标
        # show_height = 0

        # 这个添加标签函数的话，要重写
        for rr in range(len(image_open_list)):
            im_num = im_num + 1

            img_open = image_open_list[rr]
            # img_open=img_png_list[rr]
            img_png = img_png_list[rr]
            width1, height1 = img_open.size
            # if im_num==1:
            #     print(f"{self.frame_r_width - width1}")

            # height1 = resize_pic_num(height1, width1)

            # 这里获取图片名称
            pic_name = str(filelist[rr])[int(str(filelist[rr]).rfind("/") + 1):len(str(filelist[rr]))]

            # 名称坐标等于

            nay = self.show_height + height1 + 2

            # width1=700
            # show_height = height1 + 5
            # image1 = canvas.create_image(30, 150, image=img_png, anchor=W)
            # image1 = canvas.create_image(0,0,anchor="nw",image=img_png)
            # int((self.frame_r_width - width1) / 2)
            locals()[f"image{im_num}"] = canvas.create_image(0, self.show_height, anchor="nw", image=img_png,
                                                             tag=f"tag{im_num}")

            locals()[f"pic_name{im_num}"] = canvas.create_text(nax, nay, text=f"{pic_name}", fill='#000000',
                                                               anchor="nw", font=('微软雅黑', 10, 'normal'))


            self.creat_entry_and_tag_frame(canvas, im_num, pic_name, clsdoc, choose_num, main_win, nay,
                                      nax1, dirname, nax2)



            # print(locals()[f"pic_name{im_num}"].size)
            # print(show_height)
            # print(canvas.create_image(0, show_height, anchor="nw", image=img_png))
            # print(locals()[f"image{im_num}"])
            self.show_height = self.show_height + height1 + self.jgz_value


    def image_show_main_frame_program_cls_in(self,firedir,choose_num=0):

        # print(choose_num)
        #这里都可以写进函数里面
        docxfile = f"{BASC}/word文档/图片名称筛选收集.docx"
        clsdoc = DocHandle(docxfile)
        main_win = tkinter.Tk()
        main_win.iconbitmap(f'{BASC}/icon/image_file.ico')


        #这是显示窗口的宽度的
        # frame_kd=700
        # frame_gd=710
        #
        #
        # # 这里，是要写进初始化的，因为你要写不一样的窗口的
        # #每张图片的间隔值
        # jgz_value=30
        # num_k=0

        if self.firdir is None:
            self.firdir=firedir


        #图片文件夹名
        dirname = os.path.basename(firedir)


        # 调整窗口位置
        main_win.geometry(f"{self.frame_kd}x{self.frame_gd+70}")
        main_win.geometry("+600+15")
        # 设置窗口标题
        main_win.title(f"展示图片")


        filelist = se_every_file_in_normal(firedir, file_type=1)
        # 然后这里是循环展示图片
        image_open_list = []
        img_png_list = []

        #这里也是要控制输出,这里通过后面的参数，控制输出了。
        img_png_list, image_open_list = handle_pic_choi(filelist, img_png_list, image_open_list, self.frame_gd, self.frame_kd,chov_n=self.num_k)


        the_biggest_height=0
        # the_biggest_width=0



        for mm in image_open_list:
            img_open = mm
            width1, height1 = img_open.size
            # height1=resize_pic_num(height1, width1,frame_kd)
            the_biggest_height=the_biggest_height+height1+self.jgz_value


            # if the_biggest_width is None:
            #     the_biggest_width = width1
            # else:
            if width1>self.the_biggest_width:
                self.the_biggest_width = width1

        self.frame_r_width=int(self.the_biggest_width+self.add_w)
        # cv = tkinter.Canvas(main_win, bg="white", width=300, height=250)
        canvas = tkinter.Canvas(main_win, width=int(self.the_biggest_width+self.add_w), height=the_biggest_height, bg="white")
        # canvas = tkinter.Canvas(main_win, width=650,bg="white")
        # canvas = tkinter.Canvas(main_win,bg="white")

        ybar = tkinter.Scrollbar(main_win)
        xbar = tkinter.Scrollbar(main_win,orient='horizontal')
        # scroll_x = ttk.Scrollbar(orient='horizontal')

        ybar.pack(side="right", fill="y")
        xbar.pack(side="bottom", fill="x")


        # event_text = tk.Text(root, height=10, width=10)
        ybar.config(command=canvas.yview)
        xbar.config(command=canvas.xview)
        canvas.config(yscrollcommand=ybar.set)
        canvas.config(xscrollcommand=xbar.set)
        # canvas.create_window(620, 0, height=770, width=30, window=ybar,anchor="nw")
        # ybar.grid(row=1, column=2, sticky="ns")
        # canvas.bind("<Right>", partial(event2, canvas))

        # canvas.bind("<Key-Down>", partial(event2, canvas))
        # canvas.bind("<Key>", partial(key))



        #www
        self.__frame_button_show(image_open_list,img_png_list,filelist,canvas,clsdoc,
                          choose_num,main_win,dirname)


        # canvas.config(scrollregion=(0, 0, 300, 800))  # 设置画布可以滚动的范围
        canvas.config(scrollregion=canvas.bbox('all'))  # 设置画布可以滚动的范围
        canvas.config(yscrollincrement=90)
        # canvas.config(xscrollincrement=6)
        # canvas.grid(row=1, column=0, columnspan=2)
        canvas.pack(side="left", fill="both")
        canvas.bind("<MouseWheel>", partial(event1, canvas))
        canvas.bind("<Down>", partial(event2, canvas))


        main_win.mainloop()

    # call(["python", f"{BASC}/def_pack/mouse_scroll.py"])

    # try:
    #     keyboard.hook(abc)
    #     keyboard.wait('esc')
    #     print("你按下esc键，程序结束")
    # except Exception as ess:
    #     print(f"自动截图运行出错,错误信息：\n{ess}")

class ImageShowMainFrameProgram_PDF_READ(ImageShowMainFrameProgram):
    def __init__(self,ha1,ha2,firdir):
        super(ImageShowMainFrameProgram_PDF_READ, self).__init__()
        self.firdir = firdir
        #这里是得到长宽比例的
        self.ax,self.ay=self.__get_pic_x_y()


        # 1就是，展示的图片比例，是原图片的长宽比。
        self.num_k = 1

        #窗口的宽度，到时候可能需要根据去修改一下
        self.frame_kd = PDF_WIDTH

        # 这是图片的宽度
        self.widthaa = int(self.frame_kd - 20)

        #这是转换后的高度比例
        self.tr_ha1, self.tr_ha2,self.height12=self.__transfer_rate(self.ax,self.ay,ha1,ha2)



        self.tag_rcc_num=0

        #这是一个变化函数，看截到第一个，还是第二个的
        self.c_num=0

        #这是获取的一个函数
        self.dicmm=[]
        self.norm_y=self.ay

        #这是保存图片的计数的
        self.save_pic_count=0




        self.dirname = os.path.basename(self.firdir)
        self.out_dir=f"F:/自动截图/{self.dirname}"
        self.__creat_not_exist_dir()

        self.save_show_count=0

        # 这里要有一个重新计算count的函数
        self.__recount_save_num()

    #重新计算函数
    def __recount_save_num(self):
        files = os.listdir(self.out_dir)
        files = natsorted(files, alg=ns.PATH)
        if len(files)>0:
            self.save_pic_count=len(files)


    #这是找到第一个图片，得到它的长宽的
    def __get_pic_x_y(self):
        files = os.listdir(self.firdir)
        files = natsorted(files, alg=ns.PATH)
        one_pic=f"{self.firdir}/{files[0]}"
        im12 = Image.open(one_pic)
        width1, height1 = im12.size
        return width1, height1


    #创建文件夹
    def __creat_not_exist_dir(self):
        if not os.path.exists(self.out_dir):
            print("输出文件夹不存在，帮你自动创建好了")
            print("==================================")
            os.mkdir(self.out_dir)

    #转换比例
    #x，y，图形界面输入的比例，这个要自己输入的,ha1,2也是自己输入的行比例
    def __transfer_rate(self,x,y,ha1,ha2):
        # self.frame_gd
        height12 = round((((self.widthaa) * y) / x)+0.5)
        tr_ha1 = round((((self.widthaa) * ha1) / x)+0.5)
        tr_ha2 = round((((self.widthaa) * ha2) / x)+0.5)
        # tr_ha1=(ha1*height12)/y
        return tr_ha1,tr_ha2,height12

    def __clip_pdf_pic(self,pic_name_g,clip_list):
        pic_file= f"{self.firdir}/{pic_name_g}"
        im12 = Image.open(pic_file)
        width1, height1 = im12.size
        im1 = im12.crop((0, int(clip_list[0]), int(width1),int(clip_list[1])))
        im1 = im1.convert("RGB")
        self.save_pic_count=self.save_pic_count+1
        aki=str(pic_name_g).split(".")[0]
        # print(f"{aki}")
        outname=f"{self.out_dir}/{self.save_pic_count}[{aki}].jpg"
        im1.save(outname)

        self.save_show_count=self.save_show_count+1
        if self.save_show_count==6:
            os.system('cls')
            self.save_show_count=0

        print(f"保存图片：{self.save_pic_count}[{aki}].jpg\n")



    #这是矩形图案绑定函数的
    def __tag_rcc_func(self,topa,bota,pic_name,event):

        #这里不对，要返回的是，那个图片的原帧率的高度低，还要根据原图片名来做选择的。。。

        if self.c_num==0:
            self.dicmm = []
            cho_y=topa
            cho_y2=round(((self.norm_y*cho_y)/self.height12)+0.5)
            self.dicmm.append(cho_y2)
            self.c_num =1
            print("\n已点击第一个")
        else:
            cho_y = bota
            cho_y2 = round(((self.norm_y * cho_y) / self.height12)+0.5)
            self.dicmm.append(cho_y2)
            #因为这里已经达到两个了，所以要执行一个函数。
            self.c_num = 0


            #这里执行一个函数。应该是根据来截图的。所以这里，应该是执行一个截图函数。。。
            self.__clip_pdf_pic(pic_name, self.dicmm)


    #要修改的函数，类里面的
    #这是创建标签跟输入框的
    def creat_entry_and_tag_frame(self,canvas,im_num,pic_name,clsdoc,choose_num,main_win,nay,
                                  nax1,dirname,nax2):

        #图片的坐标0,self.show_height
        #把一页图片的所有点，都绘制出来
        point_line=[]
        rect_point2=[]
        total_y=self.show_height+self.height12
        hadd=self.show_height+self.tr_ha1

        #这里是要绘制所有y坐标，
        y_list=[self.show_height+self.tr_ha1,]
        while hadd<total_y:
            hadd=hadd+self.tr_ha2
            if hadd<total_y:
                y_list.append(hadd)

        #这里是绘制出全部坐标
        for pp in range(len(y_list)):
            komm=y_list[pp]
            line_point1=[]

            tua1=(0,komm)
            tua2=(self.widthaa,komm)


            if int(pp+1)<len(y_list):
                rect_point=[]
                komm2 = y_list[int(pp+1)]
                rect_point = [2,komm,self.widthaa,komm2]
                rect_point2.append(rect_point)
            line_point1.append(tua1)
            line_point1.append(tua2)
            point_line.append(line_point1)

        #这里就对每一页，加好横线了，之后还要加个虚空的tag，点击的时候，就可以截图。
        # for tt in point_line:
        #
        #     canvas.create_line(tt, fill="red",width=5)

        # s_hy=self.show_height.copy()
        #然后这里，绘制出所有的框
        for rcc in rect_point2:
            self.tag_rcc_num=self.tag_rcc_num+1
            x1,y1,x2,y2=rcc
            y1k=y1-self.show_height
            y2k=y2-self.show_height
            canvas.create_rectangle(x1,y1,x2,y2, width=6,fill='', dash=(1,1),outline='LightGrey',activefill = '#F0FFFF',tag=f"tag_rcc{self.tag_rcc_num}")
            canvas.tag_bind(f"tag_rcc{self.tag_rcc_num}", '<Button-1>',
                            partial(self.__tag_rcc_func,y1k,y2k,pic_name))


class PdfViewFrameProgram(ImageShowMainFrameProgram):
    def __init__(self,firdir):
        super(PdfViewFrameProgram, self).__init__()

        self.firdir = firdir

        # 1就是，展示的图片比例，是原图片的长宽比。
        self.num_k = 1

        # 窗口的宽度，到时候可能需要根据去修改一下
        self.frame_kd = PDF_WIDTH

        self.dirname = os.path.basename(self.firdir)
        self.out_dir = f"F:/自动截图/{self.dirname}"





def image_show_main_frame_program(firedir,choose_num=0):
    clsyy=ImageShowMainFrameProgram()
    clsyy.image_show_main_frame_program_cls_in(firedir,choose_num=choose_num)

def image_pdf_fitle_program(firedir,ha1,ha2):
    clsyy=ImageShowMainFrameProgram_PDF_READ(ha1,ha2,firedir)
    clsyy.image_show_main_frame_program_cls_in(firedir)


def pdf_view_rename_program(firedir):
    clsyy = PdfViewFrameProgram(firedir)
    clsyy.image_show_main_frame_program_cls_in(clsyy.out_dir,choose_num=2)

def start_space_mouse_scroll_contral():
    space_contral_scroll()

#筛选一般的图片名，就只能点击图片的
#这是正常的展示图片
def show_pic_frame_program(firedir):
    # image_show_main_frame_program(firedir)
    # kk=[]
    # kk.append(firedir)
    #
    # kk=tuple(kk)

    kk=(firedir,)
    # print(kk)
    thread1 = threading.Thread(name='t1', target=image_show_main_frame_program, args=(kk))
    # thread2 = threading.Thread(name='t2', target=start_space_mouse_scroll_contral, args=())
    thread1.start()  # 启动线程1
    # thread2.start()  # 启动线程2


#这是做视频的图像的筛选，及加标签的
def video_pic_filter(firedir):
    # image_show_main_frame_program(firedir, choose_num=1)
    kk = (firedir,)
    #后面是传递关键字实参，指定参数的
    thread1 = threading.Thread(name='t1', target=image_show_main_frame_program, args=(kk),kwargs={'choose_num': 0})
    # thread2 = threading.Thread(name='t2', target=start_space_mouse_scroll_contral, args=())
    thread1.start()  # 启动线程1
    # thread2.start()  # 启动线程2

#这是重命名图片标签的
def rename_pic_way(firedir):
    # image_show_main_frame_program(firedir, choose_num=1)
    kk = (firedir,)
    #后面是传递关键字实参，指定参数的
    thread1 = threading.Thread(name='t1', target=image_show_main_frame_program, args=(kk),kwargs={'choose_num': 1})
    # thread2 = threading.Thread(name='t2', target=start_space_mouse_scroll_contral, args=())
    thread1.start()  # 启动线程1
    # thread2.start()  # 启动线程2

if __name__ == '__main__':
    #筛选一般的图片名，就只能点击图片的

    # firedir=f"{BASC}/image"
    # firedir=f"{BASC}/image1"


    firedir="F:/"
    # video_pic_filter(firedir)
    rename_pic_way(firedir)
    pass